#pragma once
#include <iostream>
#include <string>
#include <unordered_map>
#include <utility>
#include <unistd.h>
#include <sys/types.h>
#include <sys/socket.h>

std::string GetQuery()
{
    std::string query;
    std::string method = getenv("METHOD");

    if ("GET" == method) {
        query = getenv("QUERY");
    }
    else if ("POST" == method)
    {
        int content_length = atoi(getenv("CONTENT_LENGTH"));

        while (content_length--)
        {
            char ch = 0;
            read(0, &ch, 1);
            query.push_back(ch);
        }
    }
    else {}

    return query;
}

static bool CutString(const std::string& src, std::string* out1, std::string* out2, std::string sep)
{
    size_t pos = src.find(sep);
    if (pos == std::string::npos)
        return false;

    if (out1)
        *out1 = src.substr(0, pos);
    if (out2)
        *out2 = src.substr(pos + sep.size());

    return true;
}

static std::pair<std::string, std::string> GetKV(std::string& src, std::string sep = "=")
{
    size_t pos = src.find(sep);

    if (pos == std::string::npos)
        return std::make_pair("error", "cannot find kv");

    return std::make_pair(src.substr(0, pos), src.substr(pos + sep.size()));
}